#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @creat_time      : 2023/9/22 10:43
# @author          : lijiantao
# @filename        :  / 
# @description     :
import json
import os
def json2yolo(jsonpath, yolo_path):
    json_data = json.loads(open(jsonpath).read())
    # print(json_data)
    class_mapping={}
    for i in range(len(json_data["categories"])):
        class_mapping[json_data["categories"][i]] =i
    if not os.path.exists(yolo_path):
        os.mkdir(yolo_path)
    with open(yolo_path+"/classes.txt", "w") as f:
        f.write("\n".join(class_mapping.keys()))
    print(class_mapping)
    num=len(json_data["annotations"])
    for item in json_data["annotations"]:
        image_name = item["image_name"]
        image_width = item["image_width:"]
        image_height = item["image_height"]
        # print(image_name, image_width, image_height)
        yolo_annotations= []

        for bbox in item["bbox"]:
            x = bbox["left"]
            y = bbox["top"]
            height = bbox["height"]
            width = bbox["width"]
            class_id = bbox["class"]

            yolo_x = (x+width/2)/image_width
            yolo_y = (y-height/2)/image_height
            yolo_width = width/image_width
            yolo_height = height/image_height
            yolo_class = class_id
            yolo_annotations.append(" ".join([str(yolo_class), str("{:.6f}".format(round(yolo_x, 6))), str("{:.6f}".format(round(yolo_y, 6))), str("{:.6f}".format(round(yolo_width, 6))), str("{:.6f}".format(round(yolo_height, 6)))]))
        num-=1
        print("还剩下{}个标签未转换".format(num) )

        with open(yolo_path+'/'+image_name[:-4]+".txt", "w") as f:
            f.write("\n".join(yolo_annotations))

if __name__ == '__main__':
    json2yolo("annotations.json", "./label")